﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace ScanSystemLogForm
{
    public class BinnarySerialize
    {
        ///<summary>
        /// 把对象序列化为字节数组
        ///</summary>
        public static byte[] SerializeObject(object obj)
        {
            if (obj == null)
                return null;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Close();
            return bytes;
        }
        ///<summary>
        /// 把字节数组反序列化成对象
        ///</summary>
        public static T Deserialize<T>(byte[] bytes) where T : class, new()
        {
            T obj = null;
            if (bytes == null)
                return obj;
            MemoryStream ms = new MemoryStream(bytes);
            ms.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                obj = (T)formatter.Deserialize(ms);
            }
            catch (Exception ex)
            {
                obj = null;
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            ms.Close();
            return obj;
        }

        /// <summary>
        /// 保存序列化的对象到文件中
        /// </summary>
        /// <param name="path"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Save<T>(string path, T value) where T : class, new()
        {
            //如果不存在创建文件
            FileStream fs;
            if (!File.Exists(path))
            {
                try
                {
                    fs = File.Create(path);
                }
                catch
                {
                    return false;
                }
            }
            //如果存在则打开
            else
            {
                try
                {
                    fs = File.Open(path, FileMode.Open, FileAccess.Write);
                }
                catch
                {
                    return false;
                }
            }
            //写文件
            byte[] buffer = SerializeObject(value);
            try
            {
                for (long i = 0; i < buffer.LongLength; i++)
                    fs.WriteByte(buffer[i]);
            }
            catch
            {
                return false;
            }
            fs.Close();
            return true;
        }

        /// <summary>
        /// 从文件中读取序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T Read<T>(string path) where T : class, new()
        {
            FileStream fs;
            try
            {
                fs = File.OpenRead(path);
            }
            catch
            {
                return null;
            }
            //读入缓存
            System.Collections.Generic.List<byte> bl = new System.Collections.Generic.List<byte>();
            int b = fs.ReadByte();
            while (b != -1)
            {
                bl.Add((byte)b);
                b = fs.ReadByte();
            }
            fs.Close();
            return Deserialize<T>(bl.ToArray());
        }
    }
}